import { ref } from "vue";
import {
  newReservationValid,
  type IReqCreateReservation,
} from "@/validator/reservation.valid";
import { validByField, validAll } from "@/utils/valid";

export interface IProduct {
  name: string;
  price: number;
  actualPrice: number;
  quantity: number;
}

const initModel = (): IReqCreateReservation => {
  return {
    reservationDateTime: "",
    phone: "",
    name: "",
    serviceType: 0,
    priority: 0,
    products: [] as IProduct[],
    employee: "",
    deposit: 0,
    desc: "",
  };
};

const useReservation = () => {
  const newReservationModel = ref({
    reservationDateTime: {
      value: "",
      ruleMessage: "",
      valid: (value: string) => {
        newReservationModel.value.reservationDateTime.ruleMessage =
          validByField("reservationDateTime", value, newReservationValid.shape);
        return newReservationModel.value.reservationDateTime.ruleMessage === "";
      },
    },
    phone: {
      value: "",
      ruleMessage: "",
      valid: (value: string) => {
        newReservationModel.value.phone.ruleMessage = validByField(
          "phone",
          value,
          newReservationValid.shape
        );
        return newReservationModel.value.phone.ruleMessage === "";
      },
    },
    name: {
      value: "",
      ruleMessage: "",
      valid: (value: string) => {
        newReservationModel.value.name.ruleMessage = validByField(
          "name",
          value,
          newReservationValid.shape
        );
        return newReservationModel.value.name.ruleMessage === "";
      },
    },
    serviceType: {
      value: 0,
      ruleMessage: "",
      valid: (value: number) => {
        return true;
      },
    },
    priority: {
      value: 0,
      ruleMessage: "",
      valid: (value: number) => {
        return true;
      },
    },
    products: {
      value: [] as IProduct[],
      ruleMessage: "",
      valid: (value: []) => {
        return true;
      },
    },
    employee: {
      value: "",
      ruleMessage: "",
      valid: (value: string) => {
        return true;
      },
    },
    deposit: {
      value: 0,
      ruleMessage: "",
      valid: (value: number) => {
        return true;
      },
    },
    desc: {
      value: "",
      ruleMessage: "",
      valid: (value: string) => {
        return true;
      },
    },
  });

  const doValid = (): boolean => {
    return validAll(newReservationModel.value, newReservationValid);
  };

  const reset = () => {
    const keys = Object.keys(newReservationModel.value);
    keys.forEach((key) => {
      if (typeof newReservationModel.value[key].value === "number")
        newReservationModel.value[key].value = 0;
      else if (typeof newReservationModel.value[key].value === "string")
        newReservationModel.value[key].value = "";
      newReservationModel.value[key].ruleMessage = "";
    });
  };

  return {
    newReservationModel,
    doValid,
    reset,
  };
};

export default useReservation;
